import React from 'react'
// 引入编辑器组件
import BraftEditor from 'braft-editor'
// 引入编辑器样式
import 'braft-editor/dist/index.css'
import './index.less'
import AliyunOSSUpload from '@/components/AliyunOSSUpload'
import { UploadOutlined } from '@ant-design/icons';
import {Button } from 'antd';
import { ContentUtils } from 'braft-utils'

export default class EditorDemo extends React.Component {

  state = {
    // 创建一个空的editorState作为初始值
    editorState: BraftEditor.createEditorState(this.props.content ?? null)
  }

  /* async componentDidMount () {
      // 假设此处从服务端获取html格式的编辑器内容
      const htmlContent = await fetchEditorContent()
      // 使用BraftEditor.createEditorState将html字符串转换为编辑器需要的editorStat
      this.setState({
          editorState: BraftEditor.createEditorState(htmlContent)
      })
  } */

  /* submitContent = async () => {
      // 在编辑器获得焦点时按下ctrl+s会执行此方法
      // 编辑器内容提交到服务端之前，可直接调用editorState.toHTML()来获取HTML格式的内容
      const htmlContent = this.state.editorState.toHTML()
      const result = await saveEditorContent(htmlContent)
  }
*/
  //编辑器内容改变
  handleEditorChange = (editorState) => {
    //更新编辑器状态
    this.setState({ editorState })
    //要判断输入的内容，如果有内容，设置输入的内容，如果没有内容，设置成空字符串
    //即使没有内容editorState.toHTML()也是一对空标签
    if (!editorState.isEmpty()) {
      //调用父组件的方法，将编辑器输入的内容传递回去
      const content = editorState.toHTML()
      this.props.setDetails(content)
    } else {
      this.props.setDetails('')
    }

    // console.log(content);


  }
  //图片上传完成后执行此方法，用来在编辑器中显示图片
  insertImage=url=>{
    this.setState({
      editorState: ContentUtils.insertMedias(this.state.editorState, [{
        type: 'IMAGE',
        url
      }])
    })
  }

  render() {
    //自定义控件-插入图片
    const extendControls = [
      {
        key: 'antd-uploader',
        type: 'component',
        component: (
          <AliyunOSSUpload accept="image/*" showUploadList={false} insertImage={this.insertImage}>
            <button type="button" className="control-item button upload-button" data-title="插入图片">
              插入图片
            </button>
          </AliyunOSSUpload>
        )
      }
    ]

    const { editorState } = this.state
    return (
      <div className="my-editor">
        <BraftEditor
          value={editorState}
          onChange={this.handleEditorChange}
          extendControls={extendControls}
        />
      </div>
    )

  }

}